#include "fileHelper.h"
#include "commdef.h"

bool GetFileInfomationU8( const char* path, WIN32_FIND_DATA_U8* fdata, bool needFileName )
{
	HANDLE hFile = FindFirstFileU8( path, fdata );
	if( hFile != INVALID_HANDLE_VALUE )
	{
		::FindClose( hFile );
		return true;
	}
	hFile = CreateFileU8( path, GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0 );
	if( hFile != INVALID_HANDLE_VALUE )
	{
		BY_HANDLE_FILE_INFORMATION info;
		bool ret = ::GetFileInformationByHandle( hFile, &info ) ? true : false;
		::CloseHandle( hFile );
		if( ret )
		{
			memcpy( fdata, &info, (char*)&info.dwVolumeSerialNumber - (char*)&info );
			return true;
		}
	}
	return (fdata->dwFileAttributes = GetFileAttributesU8( path ) ) == 0xffffffff ? false : true;
}

bool PathToDir( const char* srcPath, char* destDir )
{
	char	path[MAX_BUF] = {0};
	char*	fileName = 0;

	if( GetFullPathNameU8( srcPath, sizeof(path), path, &fileName ) == 0 || fileName == NULL )
	{
		strncpyz( destDir, srcPath, MAX_PATH_U8 );
		return false;
	}

	if( fileName - path > 3 || path[1] != ':' )
		*(fileName - 1) = 0;
	else *fileName = 0;

	strncpyz( destDir, path, MAX_PATH_U8 );
	return true;
}

void ForcePathToFileName( const char* orgPath, char* targetFileName )
{
	if( PathToFileName( orgPath, targetFileName ) )
		return;
	if( orgPath[1] == ':' )
		wsprintf( targetFileName, "(%c-drive)", *orgPath );
	else if( orgPath[0] == '\\' && orgPath[1] == '\\' )
	{
		if( !PathToFileName( orgPath + 2, targetFileName ) )
			wsprintf( targetFileName, "(root)" );
	}
	else wsprintf( targetFileName, "(unknown)" );
}

bool PathToFileName( const char* orgPath, char* targetFileName )
{
	char path[MAX_BUF] = { 0 };
	char* fileName = NULL;

	if( !GetFullPathNameU8( orgPath, sizeof(path), path, &fileName ) || fileName == NULL )
		return false;
	strncpyz( targetFileName, fileName, MAX_PATH_U8 );
	return true;
}